package com.server.questionbank.snframe.service.UsersService.Impl;

import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.service.UsersService.RegisterService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.JWT.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private UsersService usersService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false)
    public void phoneRegister(String phoneNumber, String password, String nickname, String avatar) {
        try {
            // 创建用户
            TUser user = new TUser();
            user.setPhoneNumber(phoneNumber);
            user.setPasswordHash(JwtTokenProvider.sha256(password));
            user.setNickName(nickname);
            if (usersService.insertUser(user) && avatar != null) {
                // 更新用户头像
                try {
                    usersService.updateUserAvatar(user.getUserId(), avatar);
                } catch (Exception e)
                {
                    throw new RuntimeException("头像上传文件失败", e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("注册失败", e);
        }
    }
}
